<template>
	<div style="width:100%">
		<el-tree-select :data="state.options"
					:props="{ checkStrictly: false, emitPath: false, value: 'id', label: 'orgName' }"
					placeholder="请选择机构"
					clearable
					check-strictly
					:render-after-expand="false"
					node-key="id"
					@change="changeState"
					@blur="onblur()"
					@clear="onclear()"
					@focus="onfocus()"
					@visible-change="visibleChange"
					@remove-tag="removeTag()"
					@input="change($event)"
					style="width:100%"
					v-model="state.coding">
		</el-tree-select>
	</div>
</template>
<script setup lang="ts" name="OrgSelect">
import { reactive, onMounted, watch } from 'vue'
import { systemApi } from '/@/api/sys/system-api'
const props = defineProps({
	modelValue: [String, Array],
	tenantId: String,
	clearable: {
		type: Boolean,
		default: () => true
	},
	multiple: {
		type: Boolean,
		default: () => false
	},
	filterable: {
		type: Boolean,
		default: () => false
	},
	placeholder: {
		type: String,
		default: () => ''
	},
	isDisabled: {
		type: Boolean,
		default: false
	},
	customData: {
		type: Array,
		default: () => []
	},
})
// 定义子组件向父组件传值/事件
const emit = defineEmits(['update:modelValue', 'change', 'onblur', 'onclear', 'onfocus', 'visibleChange', 'removeTag', 'input'])
const state = reactive({
	options: [] as any,
	coding: props.multiple
		? props.modelValue.split(',').filter((val: any) => {
			return val
		})
		: props.modelValue
})
// 页面加载时
onMounted(() => {
	initOrgDatas()
})
const initOrgDatas = () =>{
	systemApi.treeListByTenantId(props.tenantId).then(data => {
		if (data && data.code === 0) {
			state.options = data.data
		}
	})
}
const changeState = (aa: any) => {
	emit("update:modelValue", aa)
	emit('change', aa)
}
const onblur = () => {
	emit('onblur', function () {})
}
const onclear = () => {
	emit('onclear', function () {})
}
const onfocus = () => {
	emit('onfocus', function () {})
}
const visibleChange = (is: any) => {
	emit('visibleChange', is)
}
const removeTag = () => {
	emit('removeTag', function () {})
}
const change = (val: any) => {
	val = props.multiple ? val.join(',') : val
	emit('input', val)
}
watch(() => props.modelValue, (val) => {
	if (!val) {
		state.coding = null
	} else {
		state.coding = props.multiple ? val.split(',') : val
	}
})
watch(() => props.tenantId, (val) => {
	if (!val) {
		state.options = []
		state.coding = null
	} else {
		state.coding = null
		initOrgDatas()
	}
})
</script>